<template>
  <div class="material-order-list">
    <el-card>
      <div slot="header">
        <h2>我的材料订单</h2>
      </div>
      
      <el-table
        v-loading="loading"
        :data="orders"
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column
          prop="orderNumber"
          label="订单号"
          width="180"
        />
        
        <el-table-column
          label="材料名称"
          min-width="200"
        >
          <template slot-scope="scope">
            {{ scope.row.material ? scope.row.material.title : '未知材料' }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="totalAmount"
          label="金额"
          width="100"
        >
          <template slot-scope="scope">
            ¥{{ scope.row.totalAmount }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="status"
          label="状态"
          width="120"
        >
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="createdAt"
          label="创建时间"
          width="180"
        >
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="200"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click.stop="viewOrderDetails(scope.row)"
            >
              查看详情
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'pending'"
              size="mini"
              type="success"
              @click.stop="goToPayment(scope.row)"
            >
              去支付
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'paid' || scope.row.status === 'completed'"
              size="mini"
              type="info"
              @click.stop="downloadMaterial(scope.row)"
            >
              下载
            </el-button>
            
            <el-button
              v-if="scope.row.status === 'pending'"
              size="mini"
              type="danger"
              @click.stop="cancelOrder(scope.row)"
            >
              取消
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page.sync="currentPage"
          @current-change="handlePageChange"
        />
      </div>
      
      <!-- 空数据提示 -->
      <el-empty
        v-if="!loading && orders.length === 0"
        description="暂无订单记录"
      >
        <el-button type="primary" @click="$router.push('/materials')">浏览材料</el-button>
      </el-empty>
    </el-card>
  </div>
</template>

<script>
import { getMaterialOrders, cancelMaterialOrder, generateDownloadToken } from '@/api/material';

export default {
  name: 'MaterialOrderList',
  
  data() {
    return {
      loading: false,
      orders: [],
      total: 0,
      currentPage: 1,
      pageSize: 10
    };
  },
  
  created() {
    this.fetchOrders();
  },
  
  methods: {
    // 获取订单列表
    async fetchOrders() {
      try {
        this.loading = true;
        const response = await getMaterialOrders({
          page: this.currentPage,
          limit: this.pageSize
        });
        
        this.orders = response.data.items || [];
        this.total = response.data.total || 0;
      } catch (error) {
        this.$message.error('获取订单列表失败: ' + (error.message || '未知错误'));
      } finally {
        this.loading = false;
      }
    },
    
    // 处理页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchOrders();
    },
    
    // 获取状态类型
    getStatusType(status) {
      switch (status) {
        case 'pending':
          return 'warning';
        case 'paid':
        case 'completed':
          return 'success';
        case 'cancelled':
          return 'info';
        default:
          return 'info';
      }
    },
    
    // 获取状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending':
          return '待支付';
        case 'paid':
          return '已支付';
        case 'completed':
          return '已完成';
        case 'cancelled':
          return '已取消';
        default:
          return '未知状态';
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString();
    },
    
    // 处理行点击
    handleRowClick(row) {
      this.viewOrderDetails(row);
    },
    
    // 查看订单详情
    viewOrderDetails(order) {
      this.$router.push(`/materials/order/${order.orderNumber}`);
    },
    
    // 去支付
    goToPayment(order) {
      this.$router.push(`/payment/material/${order.orderNumber}`);
    },
    
    // 下载材料
    async downloadMaterial(order) {
      try {
        this.$message.info('正在准备下载...');
        const response = await generateDownloadToken(order.orderNumber);
        
        if (response.data && response.data.downloadUrl) {
          window.open(response.data.downloadUrl, '_blank');
          this.$message.success('开始下载材料');
        } else {
          this.$message.error('获取下载链接失败');
        }
      } catch (error) {
        this.$message.error('下载材料失败: ' + (error.message || '未知错误'));
      }
    },
    
    // 取消订单
    async cancelOrder(order) {
      try {
        await this.$confirm('确定要取消该订单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        await cancelMaterialOrder(order.orderNumber);
        this.$message.success('订单已取消');
        
        // 刷新订单列表
        this.fetchOrders();
      } catch (error) {
        if (error === 'cancel') {
          return;
        }
        this.$message.error('取消订单失败: ' + (error.message || '未知错误'));
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.material-order-list {
  .pagination-container {
    margin-top: 20px;
    text-align: center;
  }
  
  .el-table {
    margin-bottom: 20px;
    
    ::v-deep .el-table__row {
      cursor: pointer;
    }
  }
}
</style>